import { Component, Ref } from 'vue-facing-decorator'
import Render from '@/render/Render'
import toNative from '@/utils/toNative'
import {
    getModelValue,
    initModelValue,
    renderForm,
    type FormModalDto
} from '@/components/modal/Modal'
import { getKeyToEnum, ProductTypeCnEnum } from '@/const/enum'
import {
    VxeColumn,
    VxeGrid,
    VxeTable,
    type VxeColumnProps,
    type VxeColumnPropTypes,
    type VxeColumnSlots,
    type VxeColumnSlotTypes,
    type VxeGridMethods,
    type VxeTableDataRow,
    type VxeTableProps,
    type VxeTablePropTypes
} from 'vxe-table'
import Upload from '@/components/file/Upload'
import { Button, message } from 'ant-design-vue'
import { MinusCircleOutlined, PlusCircleOutlined, PlusOutlined } from '@ant-design/icons-vue'
import { h } from 'vue'
import type {
    ConfigListDto,
    HttpConfigDto,
    HttpConfigReqDto,
    PropertyDto,
    PropertyItemDto
} from '@/api/emailConfig/types'
import { wait } from '@/utils/util'
import { getHttpConfigData } from '../detail/Index'

export interface TableChildrenDto {
    originPhrase: string
    originPhraseName: string
    mapPhrase: string
}

@Component({
    emits: ['submit', 'initData']
})
export class ApiPushRule extends Render {
    @Ref()
    readonly tableRef!: VxeGridMethods

    // formData = {
    //     url: '',
    //     secretKey: '',
    //     authCode: '',
    //     reqConfig: []
    // } as HttpConfigDto

    basicFormConfig = this.initFormConfig() as FormModalDto
    initFormConfig() {
        return {
            title: '',
            width: '400px',
            theme: 'light',
            show: false,
            labelCol: {
                style: {
                    width: '8em'
                }
            },
            items: {
                url: {
                    name: '数据推送地址',
                    element: 'input',
                    placeholder: '请输入蓝工盾API推送地址',
                    required: true,
                    prepend: <Button>校验</Button>
                },
                secretKey: {
                    name: '密钥',
                    element: 'input',
                    placeholder: '请填写应用密钥，即AppSecret',
                    required: true
                },
                authCode: {
                    name: '授权码',
                    element: 'input',
                    placeholder: '请输入推送token',
                    required: true
                }
            },
            complete: async () => {
                const data = getModelValue(this.basicFormConfig)
                // await rechargeElesignAmount(data)
                // await updatePayManagerUser(data)
                // ElMessage.success('更新成功')
                // this.basicFormConfig.show = false
            },
            cancel: () => {
                // this.basicFormConfig.show = false
            },
            init: () => {
                initModelValue(this.basicFormConfig)
            }
        } as FormModalDto
    }
    basicForm = {
        validate: async () => {},
        clear: () => {},
        element: () => <> </>
    }

    treeConfig = {
        childrenField: 'children'
    }

    editConfig = {
        mode: 'cell',
        trigger: 'click',
        beforeEditMethod({ row, column }) {
            // type为非string时，父只能编辑原始字段 子不能编辑类型
            if (
                (row.type !== 'string' &&
                    row.children &&
                    column.field !== 'originPhrase' &&
                    column.field !== 'type') ||
                (row.type !== 'string' && !row.children && column.field === 'type')
            ) {
                return false
            }
            return true
        }
    } as VxeTablePropTypes.EditConfig

    originPharaseRender = {
        name: 'VxeSelect',
        options: [
            {
                label: '字符串',
                value: 'string'
            },
            {
                label: '数组',
                value: 'array'
            },
            {
                label: '对象',
                value: 'object'
            }
        ],
        events: {
            change: async (params: any) => {
                const { row, column, value } = params
                if (row.type !== 'string') {
                    row.children = [
                        {
                            originPhrase: '',
                            originPhraseName: '',
                            mapPhrase: ''
                        }
                    ]
                    await wait(300)
                    console.log(this.tableRef)
                    this.tableRef?.toggleTreeExpand(row)
                } else {
                    row.children = []
                }
            }
        }
    } as VxeColumnPropTypes.EditRender

    columns = [
        {
            field: 'type',
            title: '类型',
            editRender: this.originPharaseRender,
            treeNode: true
        },
        {
            field: 'originPhrase',
            title: '原始字段',
            editRender: {
                name: 'input'
            }
        },
        {
            field: 'originPhraseName',
            title: '原始字段名称',
            editRender: {
                name: 'input',
                enable: false
            }
        },
        {
            field: 'mapPhrase',
            title: '映射字段',
            editRender: {
                name: 'input'
            }
        },
        {
            field: 'operate',
            title: '操作',
            slots: {
                default: (data: VxeColumnSlotTypes.ContentSlotParams) => {
                    return (
                        <div>
                            {data.row.type ? (
                                <Button danger type="text" onClick={() => this.onRemoveRule(data)}>
                                    删除
                                </Button>
                            ) : (
                                <div class="flex gap-20px">
                                    <PlusCircleOutlined
                                        style="font-size: 20px;"
                                        onClick={() => this.onAddArray(data)}
                                    />
                                    <MinusCircleOutlined
                                        style="font-size: 20px;"
                                        onClick={() => this.onRemoveArray(data)}
                                    />
                                </div>
                            )}
                        </div>
                    )
                }
            }
        }
    ]

    tableData = [
        {
            type: 'string',
            originPhrase: '',
            originPhraseName: '',
            mapPhrase: '',
            children: [] as TableChildrenDto[]
        }
    ]

    // 新增类型为数组的项
    onAddArray(data: VxeTableDataRow) {
        data.items.splice(data.$rowIndex + 1, 0, {
            originPhrase: '',
            originPhraseName: '',
            mapPhrase: ''
        })
    }

    // 删除类型为数组的项
    onRemoveArray(data: VxeTableDataRow) {
        if (data.items.length === 1) {
            message.error('至少保留一个')
            return
        }
        data.items.splice(data.$rowIndex, 1)
    }

    // 类型为数组时无需编辑的单元格点击提示
    onEditDisabled() {
        message.warn('该单元格无需编辑')
    }

    onAddRule() {
        this.tableData.push({
            type: 'string',
            originPhrase: '',
            originPhraseName: '',
            mapPhrase: '',
            children: []
        })
    }

    onRemoveRule(data: VxeTableDataRow) {
        this.tableData.splice(data.rowIndex, 1)
    }

    // 整理为后端要的数据格式
    createData() {
        return new Promise((resolve, reject) => {
            const res = {
                type: 'object',
                properties: {} as PropertyDto
            } as HttpConfigReqDto

            this.tableData.forEach((i) => {
                switch (i.type) {
                case 'string':
                    if (!i.originPhrase || !i.originPhraseName || !i.mapPhrase) {
                        message.error('请填写完整')
                        reject(false)
                    }
                    res.properties[i.originPhrase] = {
                        type: 'string',
                        mapping: i.originPhraseName,
                        mappingName: i.mapPhrase
                    }
                    break
                case 'array':
                    if (!i.originPhrase || i.children.some(k => !k.originPhrase || !k.originPhraseName || !k.mapPhrase)) {
                        message.error('请填写完整')
                        reject(false)
                    }
                    res.properties[i.originPhrase] = {
                        type: 'array',
                        items: {
                            type: 'object',
                            properties: {}
                        }
                    }
                    i.children.forEach((item) => {
                        (
                            (res.properties[i.originPhrase].items as PropertyItemDto)
                                .properties as PropertyDto
                        )[item.originPhrase] = {
                            type: 'string',
                            mapping: item.originPhraseName,
                            mappingName: item.mapPhrase
                        }
                    })
                    break
                case 'object':
                    if (!i.originPhrase || i.children.some(k => !k.originPhrase || !k.originPhraseName || !k.mapPhrase)) {
                        message.error('请填写完整')
                        reject(false)
                    }
                    res.properties[i.originPhrase] = {
                        type: 'object',
                        properties: {}
                    }
                    i.children.forEach((item) => {
                        (res.properties[i.originPhrase].properties as PropertyDto)[
                            item.originPhrase
                        ] = {
                            type: 'string',
                            mapping: item.originPhraseName,
                            mappingName: item.mapPhrase
                        }
                    })
                    break
                }
            })
            resolve(res)
        })
    }

    initData(data: ConfigListDto) {
        if (data.httpConfig?.length) {
            const httpConfig = data.httpConfig[0]
            console.log(1234, httpConfig)
            initModelValue(this.basicFormConfig, httpConfig)
            if (httpConfig.respConfig) {
                const respData = getHttpConfigData(httpConfig.respConfig)
                console.log(9999, respData)
                this.tableData = respData
            }
        }
    }

    async submit() {
        await this.basicForm.validate()
        const data = getModelValue(this.basicFormConfig)
        const res = await this.createData()
        console.log(1111, data, res)
        return {
            httpConfigs: [{
                ...data,
                respConfig: JSON.stringify(res)
            }]
        }
    }

    onMounted() {
        this.basicForm = renderForm(this.basicFormConfig)
    }

    render() {
        return (
            <div>
                <div>
                    <div class="text-lg text-black-300 mb-10px">API推送规则</div>
                    {this.basicForm.element()}
                </div>
                <div class="px-20px">
                    <div class="text-base text-black-300 mb-16px">映射关系设置</div>
                    <VxeGrid
                        ref="tableRef"
                        editConfig={this.editConfig}
                        treeConfig={this.treeConfig}
                        columns={this.columns}
                        data={this.tableData}
                        onEditDisabled={this.onEditDisabled}
                    ></VxeGrid>
                    <Button class="mt-20px w-full" icon={h(PlusOutlined)} onClick={this.onAddRule}>
                        添加
                    </Button>
                </div>
            </div>
        )
    }
}

export default toNative<{}, {}>(ApiPushRule)
